import 'dart:convert';

import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/company_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail/company_detail_page.dart';
import 'package:e_reception_flutter/ui/company/company_detail/event/refresh_company_detail_page_event.dart';
import 'package:e_reception_flutter/ui/company/company_detail/widgets/company_detail_filter_button_widget.dart';
import 'package:e_reception_flutter/ui/company/company_detail_by_type_list/bean/company_detail_by_type_list_response_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail_search/company_search_detail_list_item_widget.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import '../../app_main.dart';
import 'company_detail_by_type_list_widget.dart';

class CompanyDetailByTypeListViewModel extends BasePagerViewModel<
    CompanyDetailByTypeListItemBean, CompanyDetailByTypeListResponseBean> {
  ///App删除用户
  static const String DELETE_USER_API =ServerApi.BASE_URL + "app/appRmoveUser";

  ///一键忽略
  static const String ALL_IGNORE_FACE_API =
      ServerApi.BASE_URL + "app/appIgnoreFaceUser";

  ///忽略或删除刷脸用户
  static const String SINGLE_IGNORE_OR_DELETE_API =
      ServerApi.BASE_URL + "app/appIgnoreDeleteOneFaceUser";

  final GroupPersonCntBean groupBean;

  final CompanyDetailByTypeListWidgetState state;

  ValueNotifier<StatisticsBean> statisticsValueNotifier;

  ///设置是否需要缓存
  bool noNeedCache;



  CompanyDetailByTypeListViewModel(this.state, this.groupBean,{
    this.noNeedCache
  }) : super(state) {
    statisticsValueNotifier = ValueNotifier(null);
  }

  @override
  void onDisposed() {
    super.onDisposed();
    statisticsValueNotifier?.dispose();
  }

  ///设置特别关心
  void removeVeryCare(
      BuildContext context,
      String fuid,) {
    if (StringUtils.isEmpty(fuid)) {
      VgToastUtils.toast(context, "个人信息获取失败");
      return;
    }
    VgHttpUtils.post(NetApi.SPECIAL_FOCUS_FACE_USER_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          //00取消 01关注
          "flg": "00",
          "fuid": fuid ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          VgEventBus.global.send(RefreshCompanyDetailPageEvent());
        }, onError: (msg) {
          VgToastUtils.toast(AppMain.context, msg);
        }));
  }

  ///获取顶部信息请求
  void deleteUserHttp(BuildContext context,
      {String fuid, String roleid, String userid}) {
    if (StringUtils.isEmpty(fuid)) {
      VgToastUtils.toast(context, "人员获取信息错误");
      return;
    }
    if (StringUtils.isEmpty(roleid)) {
      VgToastUtils.toast(context, "身份错误");
      return;
    }
    VgHudUtils.show(context, "删除中");
    VgHttpUtils.get(DELETE_USER_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "fuid": fuid ?? "",
          "roleid": roleid ?? "",
          "userid": userid ?? ""
        },
        callback: BaseCallback(onSuccess: (val) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, "删除成功");
          String searchDetailKey = SP_SEARCH_DETAIL+UserRepository.getInstance().getCompanyId();
          //查询缓存，缓存中有数据，在基础上删除
          SharePreferenceUtil.getString(searchDetailKey).then((userJsonStr){
            if(userJsonStr == null){
              return;
            }
            var listDynamic = jsonDecode(userJsonStr);
            List<Map<String ,dynamic>>  map = List<Map<String ,dynamic>>.from(listDynamic);
            List<CompanyDetailByTypeListItemBean> M = new List();
            map.forEach((element) => M.add(CompanyDetailByTypeListItemBean.fromMap(element)));
            List<String> fuids = List<String>();
            M?.forEach((element) {
              fuids?.add(element?.fuid);
            });
            if(fuids?.toString()?.contains(fuid)){
              // itemBeanListSearch = M;
              for(int i = 0;i<M.length ; i++){
                if(fuid == M[i]?.fuid){
                  M?.removeAt(i);
                }
              }
              String cache = jsonEncode(M);
              SharePreferenceUtil.putString(searchDetailKey, cache);
              VgEventBus.global.send(SearchRefreshEvent());
            }
          });
          VgEventBus.global.send(new MonitoringIndexPageClass());
          VgEventBus.global.send(CompanyNumBarEventMonitor());
          //刷新
          CompanyDetailPageState.of(context).noticeRefreshHttp();
        }, onError: (msg) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }));
  }

  ///忽略一张脸
  void ignoreSingleFaceHttp(BuildContext context, String fid) {
    if (StringUtils.isEmpty(fid)) {
      VgToastUtils.toast(context, "人脸数据获取失败");
      return;
    }
    VgHttpUtils.post(SINGLE_IGNORE_OR_DELETE_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "fid": fid ?? "",
          "flg": "00", //00忽略 01删除
        },
        callback: BaseCallback(onSuccess: (val) {
//刷新
          CompanyDetailPageState.of(context).noticeRefreshHttp();
          VgToastUtils.toast(context, "忽略成功");
        }, onError: (msg) {
          VgToastUtils.toast(context, msg);
        }));
  }

  ///删除一张脸
  void deleteSingleFaceHttp(BuildContext context, String fid) {
    if (StringUtils.isEmpty(fid)) {
      VgToastUtils.toast(context, "人脸数据获取失败");
      return;
    }
    VgHttpUtils.post(SINGLE_IGNORE_OR_DELETE_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "fid": fid ?? "",
          "flg": "01", //00忽略 01删除
        },
        callback: BaseCallback(onSuccess: (val) {
//刷新
          CompanyDetailPageState.of(context).noticeRefreshHttp();
          VgToastUtils.toast(context, "删除成功");
        }, onError: (msg) {
          VgToastUtils.toast(context, msg);
        }));
  }

  @override
  String getBodyData(int page) {
    return null;
  }


  @override
  String getCacheKey() {
    return ServerApi.BASE_URL + "app/appCompanyPages"+(groupBean?.groupid ?? "")+(groupBean?.groupType ?? "")+(UserRepository.getInstance().getCompanyId()+(UserRepository.getInstance().getPhone()));
  }


  @override
  bool isNeedCache() {
    if(noNeedCache!=null){
      return noNeedCache;
    }
    //缓存非搜索情况
    return StringUtils.isEmpty(state?.widget?.searchPageValueNotifier?.value )&&
        StringUtils.isEmpty(state?.companyDetailFilterNotification?.companyDetailFilterValueNotifier?.value?.getParamsStr());
  }

  @override
  Map<String, dynamic> getQuery(int page) {
    Map<String, dynamic> map = {
      "authId": UserRepository.getInstance().authId ?? "",
      "current": page ?? 1,
      "size": 20,
      "groupid": groupBean?.groupid ?? "",
      "groupType": groupBean?.groupType ?? "",
      "searchName": state?.widget?.searchPageValueNotifier?.value ?? "",
      "searchOthers": state?.companyDetailFilterNotification?.companyDetailFilterValueNotifier?.value?.getParamsStr() ?? "",
      // "isVisitor": groupBean?.visitor ?? "",
      // "visitorGroupId": groupBean?.visitorGroupId ?? "",
    };
    return map;
  }

  @override
  String getRequestMethod() {
    return HttpUtils.GET;
  }

  @override
  String getUrl() {
    return ServerApi.BASE_URL + "app/appCompanyPages";
  }

  @override
  CompanyDetailByTypeListResponseBean parseData(VgHttpResponse resp) {
    CompanyDetailByTypeListResponseBean vo =
    CompanyDetailByTypeListResponseBean.fromMap(resp?.data, isSpecialList: "特别关注" == groupBean?.groupName);
    loading(false);
    if (!isStateDisposed) {
      statisticsValueNotifier?.value = vo?.data?.statistics;
    }
    if (groupBean.isAllGroup()) {
      state?.companyDetailFilterNotification?.statisticsValueNotifier?.value =
      (vo?.data?.statistics);
    }
    return vo;
  }

  @override
  void refresh() {
    if (isStateDisposed) {
      return;
    }
    // VgEventBus.global.send(RefreshCompanyDetailPageEvent(msg: "主动刷新下公司顶部信息"));
    super.refresh();
  }

  @override
  void refreshMultiPage() {
    if (isStateDisposed) {
      return;
    }
    super.refreshMultiPage();
  }

  @override
  Stream<String> get onRefreshFailed => Stream.value(null);

  @override
  Stream<String> get onLoadFailed => Stream.value(null);
}
